/**
 * Created by linyanbin on 2018/10/5.
 */
function readTemplateAndAppend(str, data, ele) {
    // console.log(data)
    var template = Handlebars.compile(str);
    var html = template(data);
    // console.log(html)
    ele.append(html);
}
function readTemplateAndPrepend(str, data, ele) {
    var template = Handlebars.compile(str);
    var html = template(data);
    ele.prepend(html);
}
var url = {
    article: {
        loadRecommendUrl: '/campus/api/articles/top/5',
        loadRankUrl: '/campus/api/articles/top/6',
        loadPageUrl: '/campus/api/articles/p'
    }
}

//注册一个自定义方法
Handlebars.registerHelper("compareGreaterTo", function(v1, v2, options){
    if(v1 > v2){
        //固定写法，满足if执行{{if}}部分
        return options.fn(this);
    }else{
        //不满足条件执行{{else}}部分
        return options.inverse(this);
    }
});
Handlebars.registerHelper("compareEqualTo", function(v1, v2, options){
    if(v1 == v2){
        return options.fn(this);
    }else{
        return options.inverse(this);
    }
});
Handlebars.registerHelper("addOne", function(val, options){
    val++;
    return val;
});

// 分页组件在总记录数大于每页显示记录数时才显示
var pageGroup  = '{{#compareGreaterTo count pageSize}}'+
    '<div class="pagelist">' +
        // 上一页和首页
        '{{#compareGreaterTo currentPage 1}}<a href="javascript:void(0);" class="page last_page" data-page="1">首页</a>' +
            '{{else}}<a href="javascript:void(0);" class="page last_page disabled" data-page="1">首页</a>'+
        '{{/compareGreaterTo}}'+
        '{{#compareGreaterTo currentPage 1}}<a href="javascript:void(0);" class="page previous_page" data-page="{{prePage}}">&lt;</a>' +
            '{{else}}<a href="javascript:void(0);" class="page previous_page disabled" data-page="{{prePage}}">&lt;</a>' +
        '{{/compareGreaterTo}}'+
        // 遍历, pageIndexArray为存储页数索引的数组
        '{{#each pageIndexArray}}'+
            '{{#compareEqualTo ../currentPage this}}<a href="javascript:void(0);" class="page active" data-page="{{this}}">{{this}}</a>'+
                '{{else}}<a href="javascript:void(0);" class="page" data-page="{{this}}">{{this}}</a>'+
            '{{/compareEqualTo}}'+
        '{{/each}}'+
        // 下一页和尾页
        '{{#compareGreaterTo totalPage currentPage }}<a href="javascript:void(0);" class="page next_page" data-page="{{totalPage}}">&gt;</a>' +
            '{{else}} <a href="javascript:void(0);" class="page last_page disabled" data-page="{{totalPage}}">&gt;</a>' +
        '{{/compareGreaterTo}}'+
        '{{#compareGreaterTo totalPage currentPage }}<a href="javascript:void(0);" class="page previous_page" data-page="{{nextPage}}">末页</a>' +
            '{{else}}<a href="javascript:void(0);" class="page previous_page disabled" data-page="{{nextPage}}">末页</a>' +
        '{{/compareGreaterTo}}'+
    '</div>'+
'{{/compareGreaterTo}}';
var articlePageHtml = '<ul>' +
    '{{#each list}}<li>' +
        '<span class="blogpic">' +
            '<a href="/campus/composition_content.html?aid={{articleId}}">' +
                '<img src="/campus{{this.navgationImg}}">' +
            '</a>' +
        '</span>' +
        '<h3 class="blogtitle">' +
            '<a href="/campus/composition_content.html?aid={{articleId}}">{{this.articleTitle}}</a>' +
        '</h3>' +
        '<div class="bloginfo">' +
            '<p>{{this.articleSummary}}</p>' +
        '</div>' +
        '<div class="autor">' +
            '<span class="dtime">{{this.createTime}}</span>' +
            '<span class="viewnum">浏览（<a href="composition_content.html?aid={{articleId}}">{{this.articleViewCount}}</a>）</span>' +
            '<span class="readmore"><a href="composition_content.html?aid={{articleId}}">阅读原文</a></span>' +
    '   </div>' +
    '</li>' +
    '{{/each}}'+
    '</ul>' + pageGroup;
var commentPageHtml = '<h4>最新评论</h4>' +
    '<ul>' +
    '{{#each list}}' +
    '<li class="visitor_li">' +
        '<input type="hidden" value="{{this.commentId}}"/>'+
        '<img src="img/a2.jpg" class="visitor_img">' +
        '<p class="visitor_p">' +
            '<span class="visitor_name">{{this.user.username}}</span>' +
            '<span class="visitor_time">{{this.createTime}}</span>' +
            '<span class="visitor_floor">{{addOne @index}}楼</span>' +
        '</p>' +
        '<p class="visitor_content">{{this.commentContent}}</p>' +
        '<p class="visitor_p">' +
            '<span class="visitor_reply">回复（{{this.replyCount}}）</span>' +
            '<span class="visitor_report">举报</span>' +
        '</p>' +
    '</li>' +
    '{{/each}}'+ '</ul>' + pageGroup;

function loadPageData(params) {
    var currPage = params.page;
    $.get(params.url, {
        'page': currPage,
        'size': params.size
    }, function (res) {
        // 删除原有的
        var divEle = params.ele;
        if (res.data.list.length == 0) {
            // 没数据，删除存数据的div
            divEle.remove();
            return;
        }
        divEle.children().remove();

        var totalPage = res.data.totalPage;
        res.data.prePage = currPage - 1 > 0 ? currPage - 1 : currPage;
        res.data.nextPage = currPage + 1 <= totalPage ? currPage + 1 : totalPage;
        var arr = [];
        for (var i = 1; i <= totalPage; i++) {
            arr.push(i);
        }
        res.data.pageIndexArray = arr;
        readTemplateAndAppend(params.templateHtml, res.data, divEle);
        // 为分页标签元素添加事件
         divEle.on('click', '.page', function () {
            var bool = $(this).hasClass('disabled');
            if (bool) {
                return;
            } else {
                params.page =  $(this).data('page');
                loadPageData(params);
                window.scrollTo(0, 200);
            }
        });
    }, "json");
}
